package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gomodule/redigo/redis"
	"my_gin_open/model"
	"my_go_open/utils"
	"net/http"
	"time"
)

func RateLimit(c *gin.Context) {
	rc := model.RpRate.Get()
	defer func(rc redis.Conn) {
		_ = rc.Close()
	}(rc)
	if bln, _ := utils.RedisRateLimit(
		rc,
		fmt.Sprintf("%s:rate_ip:%s", model.AppName, c.ClientIP()),
		40,
		30*time.Second,
	); !bln {
		c.AbortWithStatus(http.StatusTooManyRequests)
	}
	c.Next()
}
